<template>
  <div v-loading="loading">
    <!-- table start -->
    <!-- 新增服务 -->

    <div class="filter-container">
      <el-form
        ref="filterForm"
        :model="orderForm"
        label-width="100px"
        size="small"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item prop="name" label="商品名称：">
              <el-input v-model="orderForm.name" />
            </el-form-item>
            <el-form-item prop="proClass" label="商品分类">
              <el-select v-model="orderForm.proClass" placeholder="请选择">
                <el-option
                  v-for="(item, key) in classList"
                  :key="key"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item prop="name" label="商品类型：">
              <el-select v-model="orderForm.proName" placeholder="请选择">
                <el-option label="主商品" value="MAIN" />
                <!-- <el-option v-for="(item,key) in goodsTypeOptions" :key="key" :label="item" :value="key" /> -->
              </el-select>
            </el-form-item>
            <el-form-item prop="categoryId" label="门店">
              <el-select v-model="orderForm.shopId" placeholder="请选择">
                <el-option
                  v-for="(item, key) in shopList"
                  :key="key"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item>
          <el-button type="primary" round @click="search">查 询</el-button>
          <el-button round @click="reset">重 置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <!-- filter end -->

    <!-- table start -->
    <!-- 新增服务 -->

    <div class="table-container">
      <el-table
        :data="orderList"
        border
        stripe
        style="width: 100%"
        size="small"
        element-loading-text="加载中"
        empty-text="暂无数据"
      >
        <el-table-column prop="name" label="商品标题" />
        <el-table-column prop="defaulted" label="商品类型" width="100">
          <template slot-scope="scope">
            主商品
          </template>
        </el-table-column>
        <el-table-column :prop="businessType=='MALL'?'categoryName':'classifyName'" label="商品类目">
          <template slot-scope="scope">
            {{ scope.row.classifyName||'无' }}
          </template>
        </el-table-column>
        <el-table-column label="选择" width="150">
          <template slot-scope="scope">
            <el-radio
              v-model="form.goodsSerial"
              :label="scope.row.id"
              @change="chooseGoodsSerial(scope.row)"
            >
              {{ form.goodsSerial === scope.row.id ? "已选" : "选择" }}
            </el-radio>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <pagination-direction
        v-if="paginationConfig.total !== 0"
        :config="paginationConfig"
        @sizeschange="sizesChange"
        @pagechange="pageChange"
      />
    </div>
    <!-- table end -->
  </div>
</template>

<script>
import { productList } from '@/views/wxaMallModule/api/product'
import { getClassifyList, getGoodsList } from '@/views/wcyModule/api/product'
import { categoryTree } from '@/views/wxaMallModule/api/category'
import { getAllShop } from '@/api/shop'
import { mapGetters } from 'vuex'

export default {
  props: {
    row: {
      required: true,
      type: Object
    }
  },
  data() {
    return {
      // 配置
      goodsTypeOptions: {
        100: '实物商品',
        // 101: '配件商品',
        200: '卡/券包'
        // 300: "同城配送",
      },
      statusOptions: {
        0: '已下架',
        1: '已上架'
      },
      categoryTreeOptions: [],
      // 分页配置
      paginationConfig: {
        direction: 'center', // 分页位置
        layout: 'total, sizes, prev, pager, next, jumper', // 分页类型
        pageSizes: [10, 20], // 分页pages
        total: 0,
        page: 1, // 页数-默认1
        pageSize: 10 // 每页条数-默认10
      },
      // 状态
      loading: false,
      // 数据
      value: '',
      filterForm: {
        goodsType: 'all',
        barCode: '',
        brandId: '',
        categoryId: [0],
        goodsSerial: '',
        goodsNo: '',
        status: 1,
        title: ''
      },
      form: {
        goodsSerial: null
      },
      list: [],
      // 扫码点单相关业务
      // 门店列表
      shopList: [],
      // 分类列表
      classList: [],
      // 业务类型
      businessType: '',
      //
      orderForm: {
        name: '',
        proName: 'MAIN',
        proClass: '',
        shopId: ''
      },
      orderList: []
    }
  },
  computed: {
    ...mapGetters(['activePageForm'])
  },
  watch: {
    'activePageForm.activeModuleIndex'() {
      this.setbusinessType()
    },
    'orderForm.shopId'(val) {
      if (val) this.getProClass()
    }
  },
  created() {},
  mounted() {
    this.setbusinessType()
    this.form.goodsSerial = this.row.insideParams.goodsSerial
    // this.filterForm.goodsSerial = this.form.goodsSerial
    // this.fetchData();
    this.getCategoryOptions()
  },
  methods: {
    /**
     * 数据组
     */
    fetchData(
      pageNum = this.paginationConfig.page,
      pageSize = this.paginationConfig.pageSize
    ) {
      // 加入page
      this.filterForm.pageNum = pageNum
      this.filterForm.pageSize = pageSize
      const params = Object.assign({}, this.filterForm)
      if (
        params.categoryId.length === 0 ||
        (params.categoryId.length === 1 && params.categoryId[0] === 0)
      ) {
        params.categoryId = ''
      } else {
        params.categoryId = params.categoryId[params.categoryId.length - 1]
      }
      if (params.goodsType === 'all') params.goodsTypes = [100, 200]
      // 清除多余字段
      for (const key in params) {
        if (params[key] === '' || params[key] === 'all') {
          delete params[key]
        }
      }
      this.loading = true
      productList(params)
        .then((res) => {
          this.list = res.data.list || []
          this.paginationConfig.total = res.data.total
          this.paginationConfig.page = res.data.pageNum
        })
        .finally(() => {
          // this.filterForm.goodsSerial = null
          this.loading = false
        })
    },

    // 分页sizes改变
    sizesChange() {
      this.fetchData()
    },

    // 分页page改变
    pageChange() {
      this.fetchData()
    },

    // 获取类目tree
    getCategoryOptions() {
      return new Promise((resolve, reject) => {
        categoryTree()
          .then((res) => {
            this.categoryTreeOptions = [
              {
                categoryNo: '',
                children: undefined,
                id: 0,
                parentId: 0,
                ranking: 0,
                title: '全部'
              }
            ].concat(this.formatTreeData(res.data))
          })
          .catch((err) => {})
          .finally(() => {})
      })
    },

    // 递归children设置空
    formatTreeData(data) {
      for (var i = 0; i < data.length; i++) {
        if (data[i].children.length < 1) {
          data[i].children = undefined
        } else {
          this.formatTreeData(data[i].children)
        }
      }
      return data
    },

    /**
     * 按钮组
     */
    // 查询
    search() {
      this.getOrderList()
    },

    // 重置
    reset() {
      this.$refs.filterForm.resetFields()
      this.setbusinessType()
    },

    // 选择
    chooseGoodsSerial(row) {
      const { businessType } = this
      const params = {
        insidePage: 'goodsDetail',
        path: businessType == 'MALL' ? 'sp-mall/pages/goods-detail/index' : 'sp-mall/pages/goods-detail/index',
        mode: 'navigateTo',
        insideParams: {
          insidePageType: 'GOODSDETAIL',
          goodsSerial: businessType == 'MALL' ? row.goodsSerial : row.id,
          remark: `站内链接 > 商品详情 > ${businessType == 'MALL' ? row.title : row.name}`
        }
      }
      this.$emit('selectInsideLink', { type: 'GOODSDETAIL', params })
    },
    // 扫码点单相关逻辑
    // 获取所有门店列表
    async getShopList() {
      await getAllShop({}).then((res) => {
        this.shopList = res.data
        this.orderForm.shopId = res.data[0].id
      })
    },
    // 根据门店id获取商品分类
    async getProClass() {
      const { shopId } = this.orderForm
      await getClassifyList({ shopId, pageNum: 1, pageSize: 999 }).then((res) => {
        console.log(res.data.total > 0)
        if (res.data.total > 0) {
          this.classList = res.data.row
          this.orderForm.proClass = res.data.row[0].id
        } else {
          this.classList = [{ name: '无', id: '' }]
          this.orderForm.proClass = ''
        }
      })
    },
    async getOrderList() {
      const {
        orderForm: { proClass, shopId, name },
        paginationConfig: { pageSize, page }
      } = this
      const params = {
        classifyId: proClass,
        shopId,
        pageSize,
        page,
        name,
        status: 1
      }
      await getGoodsList(params).then((res) => {
        this.orderList = res.data.row
        this.paginationConfig.total = res.data.total
        this.paginationConfig.page = res.data.pageNum
      })
    },
    async setbusinessType() {
      await this.getShopList()
      await this.getProClass()
      await this.getOrderList()
    }

    /**
     * 状态组
     */
    /**
     * 方法组
     */
  }
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
</style>
